package com.app.lcl.test;

import java.util.HashSet;
import java.util.Set;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.app.lcl.entities.House;
import com.app.lcl.entities.Human;

public class testJunit4 {
	
	private SessionFactory sf = null;
	private Session session = null;
	private Transaction tx = null;
	/**
	 * 测试前
	 * @throws Exception
	 */
	@Before
	public void setUp() throws Exception{
		System.out.println("----初始化数据----");
		Configuration conf = new Configuration().configure();
		StandardServiceRegistryBuilder srb = new StandardServiceRegistryBuilder().applySettings(conf.getProperties());
		StandardServiceRegistry sr = srb.build();
		sf = conf.buildSessionFactory(sr);
		session = sf.openSession();
	}
	/**
	 * 测试后
	 * @throws Exception
	 */
	@After
	public void tearDown() throws Exception{
		System.out.println("----释放数据----");
		if(session.isOpen()){
			session.close();
		}
	}
	
	@Test
	public void testSaveHuman(){
		Human human1 = new Human("2204221993", "lcl", 24, true);
		Human human2 = new Human("2204221992", "yxy", 24, false);
		Set<Human> humanSet = new HashSet<Human>();
		humanSet.add(human1);
		humanSet.add(human2);
		House house1 = new House("4212", "海南");
		House house2 = new House("1231", "长春");
		Set<House> houseSet = new HashSet<House>();
		houseSet.add(house1);
		houseSet.add(house2);
		
		human1.setHouseSet(houseSet);
		human2.setHouseSet(houseSet);
		
		house1.setHumanSet(humanSet);
		house2.setHumanSet(humanSet);
		tx = session.beginTransaction();
		session.persist(human1);
		session.persist(human2);
/*级联可以只持久化一个，另一个会自动执行*/
		session.persist(house1);
		session.persist(house2);
		tx.commit();
	}
}
